package com.example.miniomultipartupload.service.impl;

import com.example.miniomultipartupload.config.MinioConfig;
import com.example.miniomultipartupload.service.ISysFileService;
import com.example.miniomultipartupload.util.FileUploadUtils;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import java.io.InputStream;
import java.util.List;


/**
 * Minio 文件存储
 * 
 * @author konglingdi
 */
@Slf4j
// @Primary
@Service
public class MinioSysFileServiceImpl implements ISysFileService
{
    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    @Qualifier("getMinioClient")
    private MinioClient client;

    /**
     * 本地文件上传接口
     * 
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file) throws Exception
    {
        String fileName = FileUploadUtils.extractFilename(file);
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(minioConfig.getBucketName())
                .object(fileName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        client.putObject(args);
        // return minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + fileName;
        return fileName;
    }

    @Override
    public void downloadFile(String fileName, ServletOutputStream outputStream) throws Exception {
        try (InputStream inputStream = client.getObject(GetObjectArgs
                .builder()
                .bucket(minioConfig.getBucketName())
                .object(fileName)
                .build());
        ) {

            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            log.error("文件下载异常");
            e.printStackTrace();
        }
    }

    @Override
    public long metedataSingleFile(String fileName) throws  Exception {
        StatObjectResponse statObjectResponse = client.statObject(StatObjectArgs.builder()
                .bucket(minioConfig.getBucketName())
                .object(fileName)
                .build());
        long size = statObjectResponse.size();

        return  size;

    }
}
